<template>
	<view class="content">
		<u-navbar placeholder title="添加商品" :autoBack="true"></u-navbar>
		<view class="from-list">
			<u-form :model="qureForm" :rules="rules" ref="uForm" :labelWidth="80">
				<u-form-item label="商品标题" prop="name">
					<u-input v-model="qureForm.name" inputAlign="right" placeholder="请输入商品标题" border="none"></u-input>
				</u-form-item>
				<u-form-item label="商品库存" prop="count">
					<u-input v-model="qureForm.count" inputAlign="right" placeholder="请输入商品库存" border="none"></u-input>
					<span style="margin-left: 8rpx;">件</span>
				</u-form-item>
				<u-form-item label="商品重量" prop="weight">
					<u-input v-model="qureForm.weight" inputAlign="right" placeholder="请输入商品重量" border="none"></u-input>
					<span style="margin-left: 8rpx;">斤</span>
				</u-form-item>
				<u-form-item label="商品规格" prop="spc">
					<u-input v-model="qureForm.spc" inputAlign="right" placeholder="请输入商品规格" border="none"></u-input>
					<!-- <span style="margin-left: 8rpx;">斤/件</span> -->
				</u-form-item>
				<u-form-item label="商品售价" prop="costPrice">
					<u-input v-model="qureForm.costPrice" inputAlign="right" placeholder="请输入进价"
						border="none"></u-input>
					<span style="margin-left: 15rpx;">￥</span>
				</u-form-item>
				<!-- <u-form-item label="配送价" prop="price">
					<u-input v-model="qureForm.price" inputAlign="right" placeholder="请输入配送价" border="none"></u-input>
					<span style="margin-left: 15rpx;">￥</span>
				</u-form-item>
				<u-form-item label="会员价" prop="vip">
					<u-input v-model="qureForm.vip" inputAlign="right" placeholder="请输入会员价" border="none"></u-input>
					<span style="margin-left: 15rpx;">￥</span>
				</u-form-item>
				<u-form-item label="供应商" prop="supplierName" @click="supplierShow = true; hideKeyboard()">
					<u-input v-model="qureForm.supplierName" disabled disabledColor="#ffffff" inputAlign="right"
						placeholder="请选择供应商" border="none"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item> -->
				<u-form-item label="商品类型" prop="typeName" @click="showSex = true; hideKeyboard()">
					<u-input v-model="qureForm.typeName" disabled disabledColor="#ffffff" inputAlign="right"
						placeholder="请选择商品类型" border="none"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="是否称重">
					<u-radio-group v-model="qureForm.sta" placement="row">
						<u-radio activeColor="#2FCC71" name="2" label="是"></u-radio>
						<u-radio style="margin-left: 20rpx;" name="1" activeColor="#2FCC71" label="否"></u-radio>
					</u-radio-group>
				</u-form-item>
			</u-form>
			<view class="img-upload">
				<view>列表图</view>
				<view style="margin-left: auto;">
					<u-upload :fileList="fileListA" @afterRead="afterReadA" :maxCount="1" @delete="deletePicA"
						:multiple="false"></u-upload>
				</view>
			</view>
			<view class="img-list">
				<view>轮播图<text style="color: #999999;font-size: 23rpx;">(最多9张)</text></view>
				<view style="margin-top: 23rpx;">
					<u-upload :fileList="fileListB" @afterRead="afterReadB" multiple :maxCount="9"
						@delete="deletePicB"></u-upload>
				</view>
			</view>
			<view class="img-upload">
				<view class="">轮播视频</view>
				<view style="margin-left: auto;">
					<u-upload accept="video" :fileList="videoList" @afterRead="videoRead" @delete="deleteVideo"
						:multiple="true" :maxCount="1">
					</u-upload>
				</view>
			</view>
			<view class="img-list">
				<view class="">商品详情</view>
				<!-- <view style="margin-top: 23rpx;">
					<u--textarea v-model="value2" placeholder="请输入商品的详细描述…" :height="100" autoHeight
						border="none"></u--textarea>
				</view> -->
				<view style="margin-top: 23rpx;">
					<!-- <u-upload :fileList="fileListC" @afterRead="afterReadC" multiple :maxCount="9"
						@delete="deletePicC"></u-upload> -->
					<u-icon name="photo" color="#999999" size="50" @click="insertImage"></u-icon>

					<editor id="editor" class="ql-container" show-img-size show-img-toolbar show-img-resize
						placeholder="请输入商品的详细描述…" @ready="onEditorReady"></editor>
				</view>
			</view>
			<u-popup :show="showSex" @close="showSex=false" mode="bottom">
				<view style="height: 800rpx;">
					<scroll-view style="height: 800rpx;" scroll-y="true" class="type-sc0rll">
						<view v-for="(item,index) in typesOptions" :key="index" @click="sexSelect(item)"
							class="type-list">
							{{item.name}}
						</view>
					</scroll-view>
				</view>
			</u-popup>
			<!-- <u-action-sheet :show="showSex" :actions="typesOptions" title="请选择商品类型" @close="showSex = false"
				@select="sexSelect">
			</u-action-sheet> -->
			<u-action-sheet :show="supplierShow" :actions="supplierOptions" title="请选择供应商" @close="supplierShow = false"
				@select="supplierSelect">
			</u-action-sheet>
		</view>
		<view class="submit-but">
			<view class="add-but" @click="submitGood">确定</view>
		</view>
	</view>
</template>

<script>
	import cellGroup from '../../uni_modules/uview-ui/libs/config/props/cellGroup'
	export default {
		data() {
			return {
				supplierShow: false,
				fileListA: [],
				fileListB: [],
				fileListC: [],
				videoList: [],
				value: 1,
				value2: '',
				fileList: [],
				showSex: false,
				qureForm: {
					id: null,
					supplierId: null,
					supplierName: null,
					type: null,
					typeName: null,
					pic: null,
					recPic: null,
					name: null,
					shortName: null,
					count: null,
					views: null,
					sales: null,
					spc: null,
					units: null,
					costPrice: null,
					price: null,
					unitPrice: 0,
					batchNo: null,
					weight: null,
					detail: null,
					status: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					mp4: null,
					sta: null,
				},
				supplierOptions: [],
				typesOptions: [],
				rules: {
					name: {
						required: true,
						message: '请填写商品标题',
						trigger: ['blur', 'change']
					}
				}
			}
		},
		onLoad(option) {
			if (option.id) {
				this.qureForm.id = option.id
				this.getList(option.id)

			}
			this.getTypes()
		},
		methods: {
			async getList(id) {
				let res = await this.$apis.procurement.getGoods(id)
				let item = res.data
				this.qureForm.id = item.id
				this.qureForm.name = item.name
				this.qureForm.supplierId = item.supplierId
				this.qureForm.supplierName = item.supplierName
				this.qureForm.type = item.type
				this.qureForm.typeName = item.typeName
				this.qureForm.count = item.count
				this.qureForm.weight = item.weight
				this.qureForm.spc = item.spc
				this.qureForm.price = item.price
				this.qureForm.costPrice = item.costPrice
				this.qureForm.sta = item.sta
				this.qureForm.vip = item.vip
				this.qureForm.unitPrice = item.unitPrice
				this.qureForm.detail = item.detail
				if (item.recPic) {
					this.qureForm.recPic = item.recPic
					this.fileListA[0] = {
						status: 'success',
						message: '',
						url: item.recPic
					}
				}
				if (item.mp4) {
					this.videoList[0] = {
						status: 'success',
						message: '',
						url: item.mp4
					}
				}
				if (item.pic) {
					let arr = item.pic.split(',')
					arr.forEach((row) => {
						this.fileListB.push({
							status: 'success',
							message: '',
							url: row
						})
					})
				}
			},
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
					this.editorCtx.setContents({
						html: this.qureForm.detail,
					});
				}).exec()

			},
			async getTypes() {
				let res = await this.$apis.procurement.addGoodsPage()
				this.supplierOptions = res.suppliers;
				this.typesOptions = res.types;
			},
			sexSelect(e) {
				this.qureForm.typeName = e.name
				this.qureForm.type = e.id
				this.showSex = false
			},
			supplierSelect(e) {
				this.qureForm.supplierName = e.name
				this.qureForm.supplierId = e.id
			},
			async afterReadA(event) {
				console.log(event);
				this.fileListA[0] = {
					...event.file,
					status: 'uploading',
					message: '上传中'
				}
				const result = await this.uploadFilePromise(event.file.url)
				console.log(result);
				this.fileListA[0] = {
					status: 'success',
					message: '',
					url: result.url
				}
				this.qureForm.recPic = result.url
			},
			deletePicA() {
				this.fileListA = []
				this.qureForm.recPic = ''
			},
			async afterReadB(event) {

				let lists = [].concat(event.file);

				let fileListLen = this.fileListB.length;

				lists.map(item => {
					this.fileListB.push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileListB[fileListLen]
					this.fileListB.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url
					}))
					fileListLen++
				}

			},
			deletePicB(event) {
				this.fileListB.splice(event.index, 1);
			},
			async afterReadC(event) {

				let lists = [].concat(event.file);

				let fileListLen = this.fileListC.length;

				lists.map(item => {
					this.fileListC.push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileListC[fileListLen]
					this.fileListC.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url
					}))
					fileListLen++
				}

			},
			deletePicC(event) {
				this.fileListC.splice(event.index, 1);
			},
			async videoRead(event) {
				let lists = [].concat(event.file);
				let fileListLen = this.videoList.length;
				lists.map(item => {
					this.videoList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				console.log(lists);
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.videoList[fileListLen]
					console.log(this.videoList);
					this.videoList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url
					}))
					fileListLen++
				}

			},
			deleteVideo(event) {
				this.videoList.splice(event.index, 1);
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://h.zhtingche.com/prod-api/common/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							'content-type': 'multipart/form-data',
							'X-Requested-With': 'XMLHttpRequest'
						},
						success: res => {
							console.log(res);
							if (res.data) {
								let obj = JSON.parse(res.data);
								console.log(obj);
								resolve(obj)
							}
						},
						fail: err => {
							console.log(err);
						}

					});
				});


			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			listToString(list, separator) {
				let strs = "";
				separator = separator || ",";
				for (let i in list) {
					strs += list[i].url + separator;
				}
				return strs != "" ? strs.substr(0, strs.length - 1) : "";
			},
			insertImage() {
				uni.chooseImage({
					count: 1,
					success: async (res) => {
						console.log(res);
						const result = await this.uploadFilePromise(res.tempFilePaths[0])
						this.editorCtx.insertImage({
							src: result.url,
							alt: '图像',
							success: function() {
								console.log('insert image success')
							}
						})
					}
				})
			},
			async submitGood() {
				try {
					let validate = await this.$refs.uForm.validate()
					if (validate) {
						this.qureForm.pic = this.listToString(this.fileListB)
						this.qureForm.mp4 = this.listToString(this.videoList)
						this.qureForm.detail = this.listToString(this.fileListC)
						console.log(this.qureForm.pic);
						this.editorCtx.getContents({
							success: async (res) => {
								console.log(res);
								this.qureForm.detail = res.html
								if (this.qureForm.id) {
									let res = await this.$apis.procurement.shopupdateGoods(this.qureForm)

									uni.showToast({
										title: '修改成功',
										icon: 'success',
										duration: 1500
									})
									setTimeout(() => {
										uni.navigateBack()
									}, 1500)
								} else {
									let res = await this.$apis.procurement.shopaddGoods(this.qureForm)
									uni.showToast({
										title: '添加成功',
										icon: 'success',
										duration: 1500
									})
									setTimeout(() => {
										uni.navigateBack()
									}, 1500)
								}
							}
						});


					}
				} catch (e) {
					console.log(e);
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	#editor {
		width: 100%;
		min-height: 3000px;
		padding-bottom: 46rpx;
		// background-color: #CCCCCC;
	}

	.content {
		padding-bottom: calc(130rpx + env(safe-area-inset-bottom) / 2) !important;
	}

	.img-upload {
		width: 688rpx;
		margin: 0 auto;
		margin-top: 31rpx;
		display: flex;
		align-items: center;
		padding: 23rpx;
		font-size: 14px;
		color: #303133;
		background-color: #fff;
		border-radius: 10rpx;
	}

	.img-list {
		width: 688rpx;
		margin: 0 auto;
		margin-top: 31rpx;
		border-radius: 10rpx;
		padding: 23rpx;
		font-size: 14px;
		color: #303133;
		background-color: #fff;
	}

	.from-list {
		width: 688rpx;
		margin: 0 auto;
	}

	.from-list ::v-deep .u-form-item {
		background-color: #fff;
		margin-top: 31rpx;
		padding: 5rpx 23rpx;
	}

	.from-list ::v-deep .u-form-item__body__right__content__slot {
		display: flex !important;
		flex-direction: row !important;
		align-items: center !important;
	}

	.from-list ::v-deep .u-radio:first-child {
		margin-left: auto !important;
	}

	.from-list ::v-deep .u-radio {
		margin-left: 20rpx;
	}

	.from-list ::v-deep .u-textarea {
		padding-left: 0;
	}

	.type-list {
		padding: 31rpx;
		border-bottom: 1px solid #d8d8d8;
		text-align: center;
		color: #666;
		font-size: 31rpx;
	}
</style>